package com.youngjun.common.security.filter;

import com.youngjun.common.security.service.RequestMapService;
import com.youngjun.common.util.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class XTokenFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(XTokenFilter.class);

    private static final String FLAG_X_TOKEN = "X-TOKEN";

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        RequestMapService requestMapService = SpringUtils.getBean(RequestMapService.class);
        boolean exists = requestMapService.mustXTokenAuthentication(httpServletRequest.getServletPath(),httpServletRequest.getMethod());

        if (exists) {
            String xToken = httpServletRequest.getHeader(FLAG_X_TOKEN);
            if (xToken == null && HttpMethod.GET.matches(httpServletRequest.getMethod())){
                xToken = httpServletRequest.getParameter(FLAG_X_TOKEN);
            }
            if (xToken == null) {
                rejectRequest(httpServletResponse);
                return;
            }
            String cookieToken = null;
            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies == null){
                rejectRequest(httpServletResponse);
                return;
            }
            for (Cookie cookie : httpServletRequest.getCookies()) {
                if (FLAG_X_TOKEN.equalsIgnoreCase(cookie.getName())) {
                    cookieToken = cookie.getValue();
                    break;
                }
            }
            if (cookieToken == null || (!cookieToken.equals(xToken))) {
                rejectRequest(httpServletResponse);
                return;
            }
        }
        chain.doFilter(request, response);
    }

    private void rejectRequest(HttpServletResponse response) {
        response.reset();
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }

    @Override
    public void destroy() {

    }
}
